﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Threading;
using System.Windows.Forms;

namespace Dot5Demo
{
    public class AppContext : ApplicationContext
    {
        public static Config SoftConfiger { get; set; }

        public static AppContext AppCtx = new AppContext();
        private const string configFileTemplate = "{0}.xml";
        private static string ConfigFile;

        private static void ReadConfig()
        {
            if (File.Exists(ConfigFile))
            {
                using (var stream = File.Open(ConfigFile, FileMode.Open))
                using (var reader = new StreamReader(stream))
                {
                    Config conf;
                    if (Utils.SerializationUtil.XmlDeserialize<Config>(reader.ReadToEnd(), out conf))
                    {
                        SoftConfiger = conf;
                        return;
                    }
                }
            }
            SoftConfiger = Config.Default;
        }

        public static void ApplyConfig()
        {
            if (SoftConfiger.Language != null)
            {
                ResourceExtensions.SetCulture(SoftConfiger.Language);
            }
        }

        private static void SaveConfig()
        {
            using var stream = File.Open(ConfigFile, FileMode.OpenOrCreate);
            using var writer = new StreamWriter(stream);
            var str = "";
            if (Utils.SerializationUtil.Serialize(SoftConfiger, out str))
            {
                writer.Write(str);
            }
            writer.Flush();
            writer.Close();
            stream.Close();
        }

        static AppContext()
        {
            AppCtx.ThreadExit += AppCtx_ThreadExit;
        }

        public static void Run()
        {
            Logger.Info("开始加载资源。。。");

            var f = new LoadingForm();
            f.BackgroundWorkAction = AppCtx.LoadingAsync;
            if (f.ShowDialog() != DialogResult.OK)
            {
                Logger.Info("资源加载窗体非正常结束，程序退出.");
                return;
            }
            AppCtx.MainForm = new MainForm();
            Logger.Info("资源加载结束。");
            Application.Run(AppCtx);
        }

        private static void AppCtx_ThreadExit(object sender, EventArgs e)
        {
            SaveConfig();
        }

        public void LoadingAsync(LoadingForm frm)
        {
            try
            {
                frm.CurrentMsg = new KeyValuePair<int, string>(10, "读取环境信息...");
                var name = Assembly.GetEntryAssembly().GetName().Name;
                var path = Path.GetDirectoryName(new UriBuilder(Application.ExecutablePath).Path);
                ConfigFile = Path.Combine(path, string.Format(configFileTemplate, name));
                frm.CurrentMsg = new KeyValuePair<int, string>(30, "读取软件配置...");
                ReadConfig();
                frm.CurrentMsg = new KeyValuePair<int, string>(40, "预加载加载数据...");
                ResourceExtensions.InitResouceInfo();
                frm.CurrentMsg = new KeyValuePair<int, string>(60, "加载数据4...");
                Thread.Sleep(1000);
                frm.CurrentMsg = new KeyValuePair<int, string>(90, "应用软件配置信息...");
                ApplyConfig();
                frm.CurrentMsg = new KeyValuePair<int, string>(100, "完成.");
                Thread.Sleep(500);
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message, "错误");
            }
        }
    }
}